<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="queryData.departmentId" @change="deptChange" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="queryData.parkId" clearable placeholder="请选择" style="width: 160px;">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="车牌号码">
          <el-input v-model="queryData.plateNumber" clearable class="filter-item" style="width: 180px;" placeholder="请输入"/>
        </el-form-item>

        <el-form-item label="车辆类型">
          <el-select v-model="queryData.type" placeholder="请选择" style="width: 90px;">
            <el-option
              v-for="item in type_options"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="选择日期" prop="dateRange">
          <el-date-picker
            v-model="queryData.dateRange"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width:333px;"
            :default-time="['00:00:00','23:59:59']"
          ></el-date-picker>
        </el-form-item>

        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row @sort-change="sortChange">

      <el-table-column align="center" label="记录id" prop="id" />

      <el-table-column align="center" label="车牌号码" prop="plateNumber" >
        <template slot-scope="scope">
          <span @mouseup="copySelected">{{ scope.row.plateNumber }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="车辆类型" prop="type" >
        <template slot-scope="scope">
          <el-tag >{{ scope.row.typeStr }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="车场名称" prop="parkName" />
      <el-table-column align="center" label="机构名称" prop="departmentName" />

      <el-table-column align="center" label="入口" prop="portName" />
      <el-table-column align="center" label="驶入时间" prop="enterTime" />

      <el-table-column align="center" label="车牌截图" prop="licensePlateImg" >
        <template slot-scope="scope">
          <img v-gallery v-if="scope.row.licensePlateImg" :src="scope.row.licensePlateImg" style="width: 5vw; height: 3vw;">
        </template>
      </el-table-column>

      <el-table-column align="center" label="出口" prop="outPortName" />
      <el-table-column align="center" label="驶出时间" prop="outTime" />

      <el-table-column align="center" label="停车时长" prop="parkingTime" />
      <!-- <el-table-column align="center" label="实收费用" prop="paidMoney" /> -->
      <el-table-column align="center" label="状态" prop="statusStr" />
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <!-- <el-button type="primary" size="small" @click="startFixingPlateNumber(scope.row)">车牌纠正</el-button> -->
          <el-button type="primary" size="small" @click="getRecordDetail(row)">停车详情</el-button>
          <el-button
            size="small"
            v-hasPermi="['admin:carcome:operationLogList2']"
            icon="el-icon-document"
            @click="handleCaozuo(row)"
            type="primary"
          >操作日志
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryData.page" :limit.sync="queryData.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :visible.sync="fixingPlateNumberDialogVisible" title="车牌纠正" width="30%">

      <el-form ref="fixingPlateNumberForm" :inline="true" :rules="fixingPlateNumberRules" :model="fixingPlateNumberForm" align="center" label-width="140px">
        <el-form-item label=" 错误的车牌号码：  " prop="plateNumber">
          <el-input v-model="fixingPlateNumberForm.plateNumber" :disabled="true" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>
        <el-form-item label=" 正确的车牌号码：  " prop="manualPlateNumber">
          <el-input v-model="fixingPlateNumberForm.manualPlateNumber" clearable class="filter-item" style="max-width: 260px;" placeholder=""/>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="fixingPlateNumberDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="fixingPlateNumber(); fixingPlateNumberDialogVisible = false">确 定</el-button>
      </span>

    </el-dialog>

    <!-- 停车详情弹框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div>
        <el-table v-loading="rizhiLodding" :data="rizhiList" >
          <el-table-column
          v-for="(item,index) in rzTableList"
          :key="index"
          :label="item.label" align="center" :prop="item.prop" :width="item.width ? item.width : ''">
            <template
            slot-scope="{row}">
              <dict-tag v-if="item.prop == 'type'" :options="dict.type.ECarcomeOperationLogType" :value="row[item.prop]"/>
              <div v-else-if="item.prop == 'img'">
                <el-image 
                  v-if="row[item.prop]"
                  style="width: 100px; height: 100px"
                  :src="row[item.prop]" 
                  :preview-src-list="[row[item.prop]]">
                </el-image>
              </div>
              <div v-else>{{row[item.prop]}}</div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="rizhiTotal>0"
          :total="rizhiTotal"
          :page.sync="rizhiQueryParams.page"
          :limit.sync="rizhiQueryParams.pageSize"
          @pagination="operationLogList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, fixingPlateNumber } from '@/api/carcome'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import { getData, } from '@/api/system/dictionary'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import {operationLogList} from "@/api/park/parkRecords";
export default {
  name: 'carcome',
  components: { Pagination },
  dicts: ['ECarcomeOperationLogType'],
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      rzTableList:[
        {label:'操作日志类型',prop:'type',},
        {label:'旧值',prop:'oldValue',},
        {label:'新值',prop:'newValue',},
        {label:'图片地址',prop:'img',},
        {label:'操作人',prop:'createBy',},
        {label:'操作时间',prop:'createTime',},
      ],//日志表格字段显示
      //日志相关
      rizhiQueryParams: {
        page: 1,
        pageSize: 10,
      },
      rizhiTotal:0,
      rizhiList:[],
      rizhiLodding:false,
      departmentList: [],//机构名称
      list: null,
      total: 0,
      listLoading: true,
      type_options: [],
      queryData: {
        page: 1,
        pageSize: 10,
        dateRange:[],
      },
      downloadLoading: false,
      dialogForm: {},
      dialogType: 1,
      name: '',
      deleteInsideRecordId: 0,
      allParkList: [],
      fixingPlateNumberForm: {
        id: '',
        plateNumber: '',
        manualPlateNumber: ''
      },
      fixingPlateNumberDialogVisible: false,
      fixingPlateNumberRules: {
        manualPlateNumber: [{ required: true, message: '车牌号码不能为空', trigger: 'blur' }]
      },
      sortMapper: {
        id: 'id',
        plateNumber: 'plate_number',
        type: 'type',
        parkName: 'parkName',
        departmentName: 'departmentName',
        portName: 'portName',
        plateImg: 'plate_img',
        outPortName: 'outPortName',
        outTimeStr: 'out_time',
        enterTimeStr: 'enter_time',
        parkingTime: 'duration',
        paidMoney: 'paid_money'
      }
    }
  },
  created() {
    if (this.$route.query.isToday) {
      const today = new Date()
      const month = today.getMonth() + 1
      let monthStr = month + ''
      if (month < 10) {
        monthStr = '0' + monthStr
      }
      const day = today.getDate()
      let dayStr = day + ''
      if (day < 10) {
        dayStr = '0' + dayStr
      }
      this.queryData.startTime = today.getFullYear() + '-' + monthStr + '-' + dayStr + ' 00:00:00'
      // this.queryData.startTime = new Date()
    }
    getDepartmentList().then(res => {
      this.departmentList = res.data || []
      this.getList()
    })
    // this.getList()
		this.getData()
  },
  methods: {
    handleCaozuo(row){//操作日志按钮
      this.rizhiQueryParams.id = row.id
      this.operationLogList()
      this.title = '操作日志'
      this.open = true
    },
    
    async operationLogList(){//操作日志数据
      this.rizhiLodding = true
      let res = await operationLogList(this.rizhiQueryParams)
      let data = res.data || {}
      let list = data.list || []
      this.rizhiTotal = data.total || 0
      this.rizhiList = list
      this.rizhiLodding = false
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId,parkType:1})
      return res.data || []
    },
		async getData(){//车辆类型
			let res = await getData('ECarcomeType')
			let list = res.data || []
			this.type_options = [{
        value: '',
        label: '全部'
      },...list]
		},
    async deptChange(e){//机构下拉选择
      let listQuery = {...this.listQuery}
      listQuery.parkId = ''
      this.listQuery = {...listQuery}
      if(!e) return this.allParkList = []
      this.allParkList = await this.getListAuthPark(e)
    },
    getList() {
      this.listLoading = true
      if(!this.queryData.dateRange) this.queryData.dateRange = []
      let queryData = {...this.queryData}
      if(this.queryData.dateRange.length){
        queryData.startTime = this.queryData.dateRange[0]
        queryData.endTime = this.queryData.dateRange[1]
      }
      delete queryData.dateRange

      fetchList(queryData).then(response => {
        let data = response.data || {}
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.queryData.page = 1
      this.getList()
    },
    getType(type) {
      if (type === 1) {
        return '临时车'
      } else if (type === 2) {
        return '固定车'
      } else if (type === 3) {
        return '内部车'
      }
      return '未知'
    },
    startFixingPlateNumber(row) {
      this.fixingPlateNumberDialogVisible = true
      this.fixingPlateNumberForm.id = row.id
      this.fixingPlateNumberForm.plateNumber = row.plateNumber
      if (row.plateNumber.length > 2) {
        this.fixingPlateNumberForm.manualPlateNumber = row.plateNumber.substr(0, 2)
      }
    },
    fixingPlateNumber() {
      if (this.fixingPlateNumberForm.manualPlateNumber) {
        this.fixingPlateNumberForm.plateNumber = this.fixingPlateNumberForm.manualPlateNumber
        fixingPlateNumber(this.fixingPlateNumberForm).then(response => {
          this.getList()
          this.fixingPlateNumberForm.manualPlateNumber = ''
        })
      }
    },
    getRecordDetail(row) {
      this.$router.push({
        path: `/park/carcomeDetail`,
        query:{id:row.id},
      })
    },

    sortChange(colInfo) {
      // 排序字段存在自定义，需要手动适配
      const sortCol = this.sortMapper[colInfo.prop] || colInfo.prop
      const sortType = colInfo.order === 'ascending' ? ' ASC' : ' DESC'
      this.queryData.sort = sortCol + sortType
      this.handleFilter()
    },

    copySelected() {
      let text = ''
      if (window.getSelection) {
        text = window.getSelection().toString()
      } else if (document.selection && document.selection.type !== 'Control') {
        text = document.selection.createRange().text
      }
      console.log('选中文本：' + text)

      if (text && text.trim()) {
        this.$set(this.queryData, 'plateNumber', text)
      }
    }

  }
}
</script>
